package com.example.butterknifedemo;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by tangjiangxu on 11/22/17.
 */

public class MyFragment extends BaseFragment {
    private static final String TAG = "MyFragment";

    @BindArray(R.array.list_data)
    String[] data;

    @BindView(R.id.lv)
    ListView lv;

    @Override
    public int getContentViewId() {
        return R.layout.activity_fragment;
    }

    @Override
    public void initAllMembersView(Bundle saveInstanceState) {
        for (String d : data) {
            Log.e(TAG, "initAllMembersView: listData" + d);
        }
        lv.setAdapter(new MyAdapter());
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return data.length;
        }

        @Override
        public Object getItem(int position) {
            return data[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(MyFragment.this.getContext()).inflate(R.layout.activity_list_item, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.title.setText(data[position]);
            return convertView;
        }
    }

    /**
     * View的持有类，通过getView中的ListItem的layout，可以自动生成
     */
    static class ViewHolder {
        @BindView(R.id.title)
        TextView title;

        /**
         * 在ViewHolder构造方法中，调用ButterKnife.bind方法
         * @param view
         */
        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
